﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace NHibernate.Audit
{
    public abstract class AbstractFixture
    {

        private static bool ConfigureLogging()
        {
            log4net.Config.XmlConfigurator.Configure();
            return true;
        }

        private static readonly bool LoggingConfigured = ConfigureLogging();
        public static readonly MappingsCache mappings = new MappingsCache().Initialize();

        protected ISessionFactory SessionFactory { get; private set; }
        protected Configuration configuration { get; private set; }
        private SchemaExport schemaExport;

        protected abstract bool FixtureRequiresNHibernate();
        protected abstract void Configure(Configuration configuration);

        protected void AddResource(Configuration cfg, string ResourceName)
        {
            var assembly = typeof(AbstractFixture).Assembly;
            cfg.AddResource(ResourceName, assembly);
        }

        protected virtual ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }

        protected virtual void OnSetUp()
        {
        }

        protected virtual void OnTearDown()
        {
        }

        protected virtual void OnFixtureSetUp()
        {
        }

        protected virtual void OnFixtureTearDown()
        {
        }


        [SetUp]
        public void SetUp()
        {
            OnSetUp();
        }

        [TearDown]
        public void TearDown()
        {
            OnTearDown();
        }

        [TestFixtureSetUp]
        public void TestFixtureSetUp()
        {
            DoNHibernateSetUp();
            OnFixtureSetUp();
        }

        [TestFixtureTearDown]
        public void TestFixtureTearDown()
        {
            DoNHibernateTearDown();
            OnFixtureTearDown();
        }

        protected void DoNHibernateSetUp()
        {
            if (this.FixtureRequiresNHibernate())
            {
                configuration = new Configuration();
                configuration.Configure("hibernate.test.cfg.xml");
                Configure(configuration);
                schemaExport = new SchemaExport(configuration);
                schemaExport.Execute(false, true, false);
                SessionFactory = configuration.BuildSessionFactory();
            }
        }

        protected void DoNHibernateTearDown()
        {
            if (null != schemaExport)
            {
                SessionFactory.Close();
                schemaExport.Execute(true, true, true);
            }
        }


    }
}
